﻿using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.Core
{
    public class AuthTicket : TableEntity
    {
        public AuthTicket()
        {

        }

        public AuthTicket(int expireMinutes, string path, string username, string roles = null)
        {
            DateTime expireDate = DateTime.UtcNow.AddMinutes(expireMinutes);
            this.PartitionKey = expireDate.ToString("yyyyMMddHHmmss");
            this.RowKey = Guid.NewGuid().ToString("N");
            this.UserName = username;
            this.Roles = roles;
            this.Path = path;
            this.ExpireDate = expireDate;
        }

        public string UserName { get; set; }

        public string Roles { get; set; }

        public string Path { get; set; }

        public DateTime ExpireDate { get; set; }

        public void Renew(int expireMinutes)
        {
            DateTime expireDate = DateTime.UtcNow.AddMinutes(expireMinutes);
        }

        public void Save(string connectionString)
        {
            var storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            TableBatchOperation batchOperation = new TableBatchOperation();
            var table = tableClient.GetTableReference("AuthTicket");
            table.CreateIfNotExists();
            batchOperation.InsertOrReplace(this);
            table.ExecuteBatch(batchOperation);
        }

        public static AuthTicket GetTicket(string connectionString, string id)
        {
            var storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            TableBatchOperation batchOperation = new TableBatchOperation();
            var table = tableClient.GetTableReference("AuthTicket");

            var query = new TableQuery<AuthTicket>();
            query = query.Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.GreaterThanOrEqual, DateTime.UtcNow.ToString("yyyyMMddHHmmss")));
            query = query.Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, id));
            var list = table.ExecuteQuery(query);
            return list.FirstOrDefault();

        }
    }
}
